/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.mqtt.broker.factory

import cool.taomu.mqtt.broker.entity.ClientSessionEntity
import cool.taomu.mqtt.broker.entity.MessageEntity
import cool.taomu.mqtt.broker.impl.PublishObservable
import cool.taomu.mqtt.broker.utils.MqttUtils
import cool.taomu.mqtt.broker.utils.impl.DataStorage
import cool.taomu.utils.inter.IObservable
import cool.taomu.utils.inter.IObserver
import cool.taomu.utils.inter.IStorage
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.mqtt.MqttMessage
import org.slf4j.LoggerFactory

class DisconnectRequest implements IProcess {
	val static LOG = LoggerFactory.getLogger(DisconnectRequest);

	val static IObservable<IObserver> observable = PublishObservable.instance;
	val IStorage cache = new DataStorage();

	override request(ChannelHandlerContext ctx, MqttMessage mqttMessage) {
		LOG.info("执行了MQTT Disconnect 命令")
		var clientId = MqttUtils.getClientId(ctx.channel);
		// 1. 清理会话 或 重新设置该客户端会话状态
		var clientSession = cache.get("mqtt-session", clientId) as ClientSessionEntity;
		this.pushWill(clientId)
		if (clientSession.cleanStatus) {
			cache.remove("mqtt-session", clientId);
		}
		ctx.close;
	}

	def pushWill(String clientId) {
		var will = cache.get("mqtt-will", clientId) as MessageEntity;
		if (will !== null) {
			observable.publish(will);
		}
	}
}
